package com.marvel.wallet.exception;

import org.slf4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class AbstractException extends RuntimeException {

    private static final long serialVersionUID = 583570023294617142L;

    private static final String pre = "---->";

    public AbstractException() {
        super();
    }

    public AbstractException(String msg) {
        super(msg);
    }


    public AbstractException(String msg, Logger logger) {
        super(msg);
        if (logger != null)
            logger.error(pre + msg);
    }

    public AbstractException(String msg, Exception e, Logger logger) {
        super(msg, e);
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            try {
                if (sw != null)
                    sw.close();

                if (pw != null)
                    pw.close();

            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        if (logger != null) {
            logger.error(pre + msg);
            logger.error(sw.toString());
        }
    }

    public AbstractException(String errCode, String errMsg) {
        super(toString(errCode, errMsg));
    }

    public AbstractException(String errCode, String errMsg, Logger logger) {
        super(toString(errCode, errMsg));
        if (logger != null)
            logger.error(pre + toString(errCode, errMsg));
    }

    public AbstractException(String errCode, String errMsg, Exception e, Logger logger) {
        super(toString(errCode, errMsg), e);
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            try {
                if (sw != null)
                    sw.close();

                if (pw != null)
                    pw.close();

            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        if (logger != null) {
            logger.error(pre + toString(errCode, errMsg));
            logger.error(sw.toString());
        }
    }

    private static String toString(String errCode, String errMsg) {
        return "{\"errCode\":\"" + errCode + "\",\"errMsg\":\"" + errMsg + "\"}";
    }
}
